﻿using System;

namespace OperationPlugins.Applications.MongoDB
{
    /// <summary>
    /// Used to build MongoDB database names.
    /// </summary>
    internal sealed class DatabaseNameBuilder
    {
        private readonly AppInstanceIndex _index;

        /// <summary>
        /// Initializes a new instance of the DatabaseNameBuilder class.
        /// </summary>
        internal DatabaseNameBuilder()
        {            
        }

        /// <summary>
        /// Initialializes a new instance of the DatabaseNameBuilder class.
        /// </summary>
        /// <param name="index">AppInstance index</param>
        internal DatabaseNameBuilder(AppInstanceIndex index)
        {
            if (index == null)
            {
                throw new ArgumentNullException("index");
            }

            _index = index;            
        }

        /// <summary>
        /// Returns the MongoDB database name.
        /// </summary>
        /// <returns>The MongoDB database name.</returns>
        internal string GetDatabaseName()
        {
            string databaseName;

            if (_index == null)
            {
                databaseName = "OperationPlugins-master";
            }
            else
            {
                if (string.IsNullOrEmpty(_index.DatabaseName))
                {
                    databaseName = string.Format("OperationPlugins-app-{0}", _index.AppId);
                }
                else
                {
                    databaseName = _index.DatabaseName;
                }
            }

            return databaseName;            
        }

    }
}
